C++ union 与 reinterpret_cast
全部标签 我写了一段代码,但我对它的输出感到困惑:#includeusingnamespacestd;classB{public:virtualvoidfoo(){cout(pb);pd1->foo();pd1->disp();}intmain(intargc,char*argv[]){B*pb=newB();func(pb);return0;}输出是:B::fooD::disp但是据我所知,pb指向类型B。而且里面没有名为disp()的函数?那么,为什么它可以访问D类中的disp()函数? 最佳答案 因为disp()不访问类的任何成员,原则
相对于static_cast,即。所以,如果我们有这两个类型转换Base*b(newDerived());Derived*d=static_cast(b);//(1)shared_ptrb(newDerived());shared_ptrd=static_pointer_cast(b);//(2)第(2)行会比第(1)行慢吗? 最佳答案 是的,它有更多的开销,因为它必须返回一个新的shared_ptr而不是一个新的原始指针。boost实现是:templateshared_ptrstatic_pointer_cast(shared_p
这是来自Intel的Embreecode中的vec3fa.h.struct__aligned(16)Vec3fa{typedeffloatScalar;enum{N=3};union{__m128m128;struct{floatx,y,z;union{inta;floatw;};};};//otherstuffinstruct};外union在做什么?内心的结合对我来说更加神秘。代码中从未引用a和w变量。看起来这提供了一种使用适当的别名读取和写入m128、x、y和z的方便且干净的方法。它是如何工作的?int是怎么参与进来的?? 最佳答案
在那种情况下可以使用const_cast还是有任何注意事项:classA{public:A():m_someData(5){}int&get(){returnm_someData;};constint&get()const{const_cast(this)->get();};private:intm_someData;};这样做的目的是让get例程可能更加复杂,并且应该避免代码重复。 最佳答案 没有。我不建议那样做。我建议您反向使用const_cast:int&get(){returnconst_cast(const_cast(*t
我对union体的理解是它的所有值都分配在同一个内存地址,并且内存空间与union体的最大成员一样大。但我不明白我们将如何实际使用它们。根据TheC++ProgrammingLanguage,这是一个最好使用union的代码.enumType{str,num};structEntry{char*name;Typet;char*s;//usesift==strinti;//useiift==num};voidf(Entry*p){if(p->t==str)couts;//...}在此之后Bjarne说:Thememberssandicanneverbeusedatthesametime,
我有一个包含2个指向不同数据类型的指针的union:union{UCHAR*_rawData;RGB*_RGBData;};typedefstructRGB{UCHARred;UCHARgreen;UCHARblue;}RGB;稍后在代码中..._rawData=newUHCAR[126];_RGBData=new_RGBData[42];//3timeslowerthanrawData所以我的问题是..像这样建立union安全吗?理论上两个变量都使用126字节,所以应该没问题,但我不确定所以我在这里问 最佳答案 联盟本身是有效的,
这是我标记的union:structUniformVariant{enumclassUNIFORM_TYPE{FLOAT,INT32,VEC2,VEC3,VEC4,MAT4}type;union{floatf;inti;glm::vec2v2;glm::vec3v3;glm::vec4v4;glm::mat4m4;}value;};如果我尝试这样使用它:voidsome_function(){UniformVariantv;some_other_function(v);}我收到编译错误useofdeletedfunction'UniformVariant::UniformVariant
如何让这个static_assert传递到我失败的代码中?我尝试了T周围const的所有排列,但我无法获得constint*。编译器总是将其解释为int*const。templateunionconst_cast_impl{usingCT=constT;static_assert(std::is_same::value,"CTisnotconstint*");Tdata;CTcdata;const_cast_impl(CTptr):cdata(ptr){}operatorT(){returndata;}};intmain(){inta=2;constint*ptr=&a;int*ptr
这个问题在这里已经有了答案:Undefinedreferencetostaticconstint(9个回答)关闭5年前。所以昨天我正在寻找SO,但找不到以下问题的答案。这种情况来self正在使用的一些代码,但这里是MCVE来演示它。我在A.h中定义了一个类A,其中只有一个静态常量。我已经在标题中对其进行了初始化。#ifndefA_H_#defineA_H_classA{public:staticconstinttest=5;~A(){};};#endif/*A_H_*/然后我有一个B类需要从A类访问publicstaticconst。在这个例子中,它将把值深度复制到一个vector中。
在一个union内的不同匿名union中具有相同名称的字段是否合法?unionFoo{union{intbar;};union{intbar;};};此代码无法通过GCC编译,但在MSVC中运行良好。 最佳答案 这是C++标准所不允许的。编译此代码的任何编译器都是不符合规范的。参见10.4.1/1:Thenamesofthemembersofananonymousunionshallbedistinctfromthenamesofanyotherentityinthescopeinwhichtheanonymousunionisde